#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);

	ps->a = (SLDatatype*)malloc(sizeof(SLDatatype) * INIT_capacity);
	if (ps->a == NULL)
	{
		perror("malloc\n");
		return;
	}
	ps->size = 0;
	ps->capacity = INIT_capacity;

}

void SLDestroy(SL* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLPrint(SL* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void CheckCapacity(SL* ps)
{
	SLDatatype* temp = (SLDatatype*)realloc(ps->a, sizeof(SLDatatype) * (ps->capacity * 2));
	if (temp == NULL)
	{
		perror("realloc\n");
		return;
	}

	ps->a = temp;
	ps->capacity *= 2;

}

void SLPushBack(SL* ps, SLDatatype x)
{
	assert(ps);

	if (ps->size == ps->capacity)
	{
		//扩容
		CheckCapacity(ps);

	}
	ps->a[ps->size] = x;
	ps->size++;

	//SLInsert(ps, ps->size, x);
}

void SLPopBack(SL* ps)
{
	assert(ps);

	if (ps->size == 0)
	{
		return;
	}

	ps->size--;

	//SLErase(ps, size-1);

}

void SLPushFront(SL* ps, SLDatatype x)
{
	assert(ps);

	//扩容
	CheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}

	ps->a[0] = x;
	ps->size++;

	//SLInsert(ps, 0, x);
	//
}

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);

	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin-1] = ps->a[begin];
		begin++;
	}

	ps->size--;

	//SLErase(ps, 0);

}

void SLInsert(SL* ps, int pos, SLDatatype x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	///扩容
	CheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}

	ps->a[pos] = x;
	ps->size++;

}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	int begin = pos;
	while (begin < ps->size)
	{
		ps->a[begin] = ps->a[begin + 1];
		begin++;
	}

	ps->size--;

}

SLDatatype SLFind(SL* ps, SLDatatype x)
{
	assert(ps);

	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLModify(SL* ps, int pos, SLDatatype x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	ps->a[pos] = x;
}